<template>
  <div class="md:flex">
    <!-- 顶部 -->
    <template v-for="(item, index) in chartCardList" :key="item.title">
      <Card
        size="small"
        :loading="loading"
        :title="item.title"
        class="md:w-1/5 w-full !md:mt-0 !mt-5"
        :class="[index + 1 < 5 && '!md:mr-5']"
        :canExpan="false"
      >
        <template #extra>
          <Tag :color="item.color">{{ item.action }}</Tag>
        </template>

        <div class="py-4 px-4 flex justify-between">
          <CountTo prefix="" :startVal="1" :endVal="item.value" class="text-2xl" />
          <Icon :icon="item.icon" :size="40" />
        </div>

        <div class="p-2 px-4 flex justify-between">
          <span style="font-size: 16px">总{{ item.title }}</span>
          <CountTo prefix="" :startVal="1" :endVal="item.total" />
        </div>
      </Card>
    </template>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';
  import { CountTo } from '/@/components/CountTo/index';
  import { Icon } from '/@/components/Icon';
  import { Tag, Card } from 'ant-design-vue';
  import { chartCardList as initialChartCardList } from '../data';
  import { gettongjilist } from '/@/api/sys/user';

  // 定义props
  defineProps({
    loading: {
      type: Boolean,
    },
  });

  // 将chartCardList转换为响应式引用
  const chartCardList = ref(initialChartCardList);

  const fetchData = async () => {
    try {
      const response = await gettongjilist();
      const data = response || {}; // 如果response为null或undefined，则data为一个空对象

      // 更新chartCardList中的数据
      chartCardList.value.forEach((item) => {
        console.log(item);

        switch (item.title) {
          case '入库数量':
            item.value = data.total_count || 0; // 如果data.total_count是null或undefined，则设置为0
            item.total = data.total_count || 0;
            break;
          case '出库数量':
            item.value = data.claimed_count || 0;
            item.total = data.claimed_count || 0;
            break;
          case '施封数量':
            item.value = data.sealed_count || 0;
            item.total = data.sealed_count || 0;
            break;
          case '剩余库存':
            item.value = data.pending_count || 0;
            item.total = data.pending_count || 0;
            break;
          case '报损数量':
            item.value = data.loss_reported_count || 0;
            item.total = data.loss_reported_count || 0;
            break;
          case '报废数量':
            item.value = data.scrapped_count || 0;
            item.total = data.scrapped_count || 0;
            break;
          default:
            break;
        }
      });
    } catch (error) {
      console.error('Failed to fetch data:', error);
    }
  };

  // 当组件挂载时，调用fetchData方法
  onMounted(() => {
    fetchData();
  });
</script>
